/*
 * buzzer.c
 *
 * Created: 26/03/2012 11:26:43
 *  Author: Dani
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>

#define BUZZER_PORT PORTD
#define BUZZER_PIN	PIND
#define BUZZER_DDR	DDRD
#define BUZZER 0b10000000

/* ------------------------------------------
	Toggle the buzzer output to make it sound
-----------------------------------------------*/

void BuzzerInit()
{
	// Buzzer pin as output.
	BUZZER_DDR |= BUZZER;
	
	// Timer 2: normal mode, pre scaler = 1024.
	TCCR2 |= 0b00000111;
	
	// Random tone
	TCNT2 = 256 - 50;
}

void BuzzerEnable(uint8_t enable)
{
	if (enable)
		TIMSK |= 0b01000000;
	else
		TIMSK &= (~0b01000000);
}

ISR (TIMER2_OVF_vect)
{
	// Toggle buzzer pin output.
	if (BUZZER_PIN & BUZZER)
		BUZZER_PORT &= ~BUZZER;
	else
		BUZZER_PORT |= BUZZER;
		
	TCNT2 = 256 - 50;
}

